package de.seminar.lego3D.views;

import java.util.Collection;
import java.util.HashSet;

import com.google.zxing.ResultPoint;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.PorterDuff.Mode;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;

public class QRCodeView  extends View {
	
	/**
	 * the context
	 */
	private Context context;
	
	/**
	 * size of the display
	 */
	private int height, width;

	/**
	 * collection containing all possible result points
	 */
	private Collection<ResultPoint> resultPoints;
	
	/**
	 * canvas to draw with
	 */
	private Canvas mCanvas;

	/**
	 * paint for the transparent bitmap
	 */
	private Paint mBitmapPaint;
	
	/**
	 * transparent bitmap
	 */
	private Bitmap mBitmap;

	/**
	 * Creates a new view for the QR-code scan.
	 * 
	 * @param context
	 */
	public QRCodeView(Context context) {
		super(context);
		this.context = context;
		Display display = ((WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
		height = display.getHeight();
		width = display.getWidth();
		resultPoints = new HashSet<ResultPoint>(5);
		
		mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
		mCanvas = new Canvas(mBitmap);
	}

	/**
	 * Draws the recognized points of the QR code.
	 */
	public void drawPoints() {
		Paint pointPaint = new Paint();
		pointPaint.setARGB(255, 255, 255, 0);
		pointPaint.setAntiAlias(true);
		pointPaint.setStyle(Style.FILL_AND_STROKE);
		pointPaint.setStrokeWidth(2);
		for (ResultPoint p : resultPoints) {
			mCanvas.drawCircle((width / 2) + p.getX(), p.getY(), 4.0f,
					pointPaint);
		}

		resultPoints = new HashSet<ResultPoint>(5);

		invalidate();
	}
	
	/**
	 * Clears the canvas object.
	 */
	public void clear() {
		mCanvas.drawColor(0, Mode.CLEAR);
		invalidate();
	}
	
	/**
	 * Adds the result point to the array list with the current detected points
	 * of the QR Code.
	 * 
	 * @param point
	 *            to add
	 */
	public void addPossibleResultPoints(ResultPoint point) {
		resultPoints.add(point);
	}

	@Override
	public void onDraw(Canvas canvas) {
		canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
	}
	
	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		super.onSizeChanged(w, h, oldw, oldh);
	}
	
}
